/**
 * Created by Jason on 2017/06/14.
 */
import constant from './constant';
import LocalDAO from './localDAO'
// import { Cache } from './polling'
import axios from 'axios'
import '@/assets/lib/bridge/bridge.js'

// const cache = Cache.getInstance();

const invoke = function (interfaceStr, params) {
  console.log(interfaceStr)
  return new Promise((resolve, reject) => {
    axios({
      method: 'post',
      url: constant.baseURL + interfaceStr,
      data: params,
      timeout: 5000
    })
    .then(result => {
<<<<<<< .mine
      console.log(result)
      let data = cache.updateBuffer(interfaceStr, params, result.data);
      resolve(data)
||||||| .r41048
      let data = cache.updateBuffer(interfaceStr, params, result.data);
      resolve(data)
=======
      // let data = cache.updateBuffer(interfaceStr, params, result.data);
      let d = result.data;
      if (d.resultCode) {
        d.resultCode == '000000' ? d = d.data : ''; // to do exception
      }

      resolve(d);
>>>>>>> .r41789
    })
    .catch(error => {
      reject(error)
    })
  })
};

/*
跳转原生登录页面
 */
const login = function (callback) {
  Bridge.callByJsUrl('gtjayyz://jumpfunc?funid=30011&jstoken=1', function (response) {
    /*
     * {'ret' :{ 'error':'0','data':{'user_code':'12342','nick_name':'sdsdsd'}},' jsToken':'1'}
     * */
    if (Number(response.error) === 1) {
      console.log('原生登录-error：', response.data);
      callback(response)
    } else {
      // alert('原生登录-data：', response);
      LocalDAO.setUserCode(response.data.user_code);
      LocalDAO.setNickname(response.data.nick_name);
      callback(response)
    }
  }, 'gtjanrng');
}

/**
获取原生接口的数据
 */
const callNativeData = function (url) {
  return new Promise(function (resolve, reject) {
    Bridge.callByJsUrl(url, function (response) {
      resolve(response)
    })
  })
};

const getStkMinList = stkCode => callNativeData(`gtjahq://getIndexListByMinute?market=${stkCode}`);

/**
获取指数分时行情
 */
const getIndexMinList = (type) => {
  switch (type) {
    case 'sh':
      return getStkMinList(constant.IndexEnum.SH)
    case 'sz':
      return getStkMinList(constant.IndexEnum.SZ)
    case 'cyb':
      return getStkMinList(constant.IndexEnum.CYB)
  }
};

// 获取三大指数实时行情
const getIndexData = () => callNativeData('gtjahq://getIndexData');

// 根据StockCode获取当前价、涨跌幅等数据
const getStockData = stkCode => callNativeData(`gtjanrng://liveStockPrice?stockcode=${stkCode}`);

// 根据模块Code获取模块涨跌幅等数据
const getModuleData = moduleCode => callNativeData(`gtjahq://getModuleData?moduleCode=${moduleCode}`);

export default {
  invoke,
  login,
  getIndexMinList,
  getIndexData,
  getStockData,
  getModuleData
}
